using GroupSix.Application.Dtos;
using GroupSix.Application.Services;
using Microsoft.AspNetCore.Mvc;

namespace GroupSix.Api.Controllers;

/// <summary>
/// 角色管理控制器
/// </summary>
[ApiController]
[Route("api/roles")]
public class RoleController : ControllerBase
{
    private readonly RoleService _roleService;

    public RoleController(RoleService roleService)
    {
        _roleService = roleService;
    }

    /// <summary>
    /// 创建角色
    /// </summary>
    /// <param name="request">创建请求</param>
    /// <returns>创建结果</returns>
    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateRoleRequestDto request)
    {
        try
        {
            // 验证模型状态
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();

                return BadRequest(new
                {
                    success = false,
                    message = "输入验证失败",
                    errors = errors
                });
            }

            var response = await _roleService.CreateAsync(request);

            return Ok(new
            {
                success = true,
                data = response,
                message = "角色创建成功"
            });
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new
            {
                success = false,
                message = ex.Message
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                success = false,
                message = $"创建角色失败: {ex.Message}"
            });
        }
    }

    /// <summary>
    /// 更新角色
    /// </summary>
    /// <param name="request">更新请求</param>
    /// <returns>更新结果</returns>
    [HttpPut]
    public async Task<IActionResult> Update([FromBody] UpdateRoleRequestDto request)
    {
        try
        {
            // 验证模型状态
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();

                return BadRequest(new
                {
                    success = false,
                    message = "输入验证失败",
                    errors = errors
                });
            }

            var response = await _roleService.UpdateAsync(request);

            return Ok(new
            {
                success = true,
                data = response,
                message = "角色更新成功"
            });
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new
            {
                success = false,
                message = ex.Message
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                success = false,
                message = $"更新角色失败: {ex.Message}"
            });
        }
    }

    /// <summary>
    /// 删除角色
    /// </summary>
    /// <param name="id">角色ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(Guid id)
    {
        try
        {
            var result = await _roleService.DeleteAsync(id);

            return Ok(new
            {
                success = true,
                message = "角色删除成功"
            });
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new
            {
                success = false,
                message = ex.Message
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                success = false,
                message = $"删除角色失败: {ex.Message}"
            });
        }
    }

    /// <summary>
    /// 获取角色列表
    /// </summary>
    /// <param name="name">角色名称（可选）</param>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">每页大小</param>
    /// <returns>角色列表</returns>
    [HttpGet]
    public async Task<IActionResult> GetList(
        [FromQuery] string? name = null,
        [FromQuery] int pageIndex = 1,
        [FromQuery] int pageSize = 10)
    {
        try
        {
            var request = new GetRolesRequestDto
            {
                Name = name,
                PageIndex = pageIndex,
                PageSize = pageSize
            };

            var response = await _roleService.GetListAsync(request);

            return Ok(new
            {
                success = true,
                data = response,
                message = "获取角色列表成功"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                success = false,
                message = $"获取角色列表失败: {ex.Message}"
            });
        }
    }

    /// <summary>
    /// 获取角色详情
    /// </summary>
    /// <param name="id">角色ID</param>
    /// <returns>角色详情</returns>
    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(Guid id)
    {
        try
        {
            var response = await _roleService.GetByIdAsync(id);

            return Ok(new
            {
                success = true,
                data = response,
                message = "获取角色详情成功"
            });
        }
        catch (InvalidOperationException ex)
        {
            return NotFound(new
            {
                success = false,
                message = ex.Message
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                success = false,
                message = $"获取角色详情失败: {ex.Message}"
            });
        }
    }

    /// <summary>
    /// 为角色分配菜单权限
    /// </summary>
    /// <param name="id">角色ID</param>
    /// <param name="menuIds">菜单ID列表</param>
    /// <returns>分配结果</returns>
    [HttpPost("{id}/menus")]
    public async Task<IActionResult> AssignMenus(Guid id, [FromBody] List<Guid> menuIds)
    {
        try
        {
            var result = await _roleService.AssignMenusAsync(id, menuIds);

            return Ok(new
            {
                success = true,
                message = "菜单权限分配成功"
            });
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new
            {
                success = false,
                message = ex.Message
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                success = false,
                message = $"分配菜单权限失败: {ex.Message}"
            });
        }
    }
} 